const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const RecipeSchema = new Schema({
  name: { type: String, required: true, index: true },
  description: { type: String },
  // 营养数据 - 可以是手动设置或通过配料计算
  calories: { type: Number, required: true },
  carbs: { type: Number, default: 0 },      // 碳水(g)
  protein: { type: Number, default: 0 },    // 蛋白质(g)
  fat: { type: Number, default: 0 },        // 脂肪(g)
  fiber: { type: Number, default: 0 },      // 纤维素(g)
  sugar: { type: Number, default: 0 },      // 糖(g)
  // 标识营养数据是否来自配料计算
  isNutritionCalculated: { type: Boolean, default: false },
  servingSize: { type: Number, default: 1 }, // 份数
  cookingTime: { type: Number },            // 烹饪时间(分钟)
  difficulty: { type: String, enum: ['简单', '中等', '困难'] }, // 难度
  imageUrl: { type: String },               // 图片URL
  // 主分类（可以是多个值）
  mealType: [{ 
    type: String, 
    enum: ['breakfast', 'lunch', 'dinner', 'snack'] 
  }],
  // 子分类（可以是多个值）
  category: [{ 
    type: String, 
    enum: ['all', 'chicken', 'bean', 'vegetable', 'grain', 'seafood', 'pork', 'beef', 'fruit', 'snack'] 
  }],
  ingredients: [{                           // 材料列表
    food: { type: Schema.Types.ObjectId, ref: 'Food' }, // 引用Food模型
    foodName: { type: String, required: true }, // 材料名称（冗余存储便于显示）
    amount: { type: String, required: true }, // 用量描述(如"100g"、"1个")
    gramWeight: { type: Number, required: true } // 实际克重，用于计算营养成分
  }],
  steps: [{                                 // 制作步骤
    order: { type: Number, required: true }, // 步骤顺序
    description: { type: String, required: true }, // 步骤描述
    imageUrl: { type: String }             // 步骤图片(可选)
  }],
  tags: [{ type: String }],                 // 标签(如"低碳水"、"适合糖尿病"等)
  suitableFor: [{                           // 适合人群的健康状况
    condition: { type: String },            // 如"糖尿病"、"高血压"等
    stage: { type: String }                 // 如"轻度"、"中度"、"重度"等
  }],
  featured: { type: Boolean, default: false }, // 是否为推荐食谱
  createdAt: { type: Date, default: Date.now },
  updatedAt: { type: Date, default: Date.now }
});

// 创建索引以支持搜索
RecipeSchema.index({ name: 'text', description: 'text', tags: 'text' });

// 计算食谱的营养成分
RecipeSchema.methods.calculateNutrition = async function() {
  try {
    const Food = mongoose.model('Food');
    
    // 初始化营养值
    let totalCalories = 0;
    let totalCarbs = 0;
    let totalProtein = 0;
    let totalFat = 0;
    let totalFiber = 0;
    let totalSugar = 0;
    
    // 遍历每个配料
    for (const ingredient of this.ingredients) {
      // 获取食物数据
      let food;
      if (ingredient.food) {
        food = await Food.findById(ingredient.food);
      } else {
        // 如果没有关联的食物ID，则通过名称进行模糊匹配
        food = await Food.findOne({ 
          $text: { $search: ingredient.foodName } 
        });
      }
      
      if (food) {
        // 计算该配料的营养贡献
        // 食材营养数据是每100克的值，所以需要乘以克重/100
        const ratio = ingredient.gramWeight / 100;
        
        totalCalories += food.calories * ratio;
        totalCarbs += food.carbs * ratio;
        totalProtein += food.protein * ratio;
        totalFat += food.fat * ratio;
        totalFiber += food.fiber * ratio;
        totalSugar += food.sugar * ratio;
      }
    }
    
    // 更新食谱的营养值
    this.calories = Math.round(totalCalories);
    this.carbs = Math.round(totalCarbs * 10) / 10;
    this.protein = Math.round(totalProtein * 10) / 10;
    this.fat = Math.round(totalFat * 10) / 10;
    this.fiber = Math.round(totalFiber * 10) / 10;
    this.sugar = Math.round(totalSugar * 10) / 10;
    
    // 标记营养值已通过配料计算
    this.isNutritionCalculated = true;
    
    return {
      calories: this.calories,
      carbs: this.carbs,
      protein: this.protein,
      fat: this.fat,
      fiber: this.fiber,
      sugar: this.sugar
    };
  } catch (error) {
    console.error('计算食谱营养成分失败:', error);
    throw error;
  }
};

// 在保存前自动计算营养成分（如果可能）
RecipeSchema.pre('save', async function(next) {
  this.updatedAt = Date.now();
  
  // 如果食材列表完整且尚未计算营养成分，则尝试计算
  if (this.ingredients && this.ingredients.length > 0 && !this.isNutritionCalculated) {
    try {
      // 检查是否有足够的信息计算营养成分
      const hasRequiredInfo = this.ingredients.every(ing => ing.gramWeight);
      
      if (hasRequiredInfo) {
        await this.calculateNutrition();
      }
    } catch (error) {
      console.error('自动计算食谱营养成分失败:', error);
      // 继续保存，即使计算失败
    }
  }
  
  next();
});

module.exports = mongoose.model('Recipe', RecipeSchema); 